package com.wyz.saas.common.gnss

import android.content.Context
import android.location.Location
import android.location.LocationListener
import android.os.Handler
import com.wyz.saas.common.gnss.AtomLocationController
import com.wyz.saas.common.gnss.AtomLocationListener
import com.wyz.saas.common.gnss.AtomLocationManager

class SingledLocationListener : AtomLocationListener, AtomLocationController {

    private val ctx: Context
    private val manager: AtomLocationManager
    private val listener: LocationListener

    @Volatile
    private var isCall: Boolean = false
    private var handler: Handler = Handler()
    private val autoCloseTask = Runnable { destroy() }
    private val delayTime: Int

    constructor(ctx: Context, listener: LocationListener, delayTime: Int = 15) {
        this.delayTime = delayTime
        this.ctx = ctx
        this.manager = AtomLocationManager(ctx, this)
        this.listener = listener
    }


    override fun onLocationChanged(
        lastLocation: Location?,
        currLocation: Location,
        provider: String,
        control: AtomLocationController?
    ) {
        if (isCall) return
        isCall = true
        if (listener is AtomLocationListener) {
            listener.onLocationChanged(lastLocation, currLocation, provider, this)
        } else {
            listener.onLocationChanged(currLocation)
        }
    }

    override fun onProviderEnabled(provider: String) {
        listener.onProviderEnabled(provider)
    }

    override fun onProviderDisabled(provider: String) {
        listener.onProviderDisabled(provider)
    }

    override fun request(): AtomLocationController {
        this.isCall = false
        if (!manager.isStart()) {
            this.manager.request()
            handler.postDelayed(autoCloseTask, delayTime * 1000L)
        } else {
            handler.removeCallbacks(autoCloseTask)
            handler.postDelayed(autoCloseTask, delayTime * 1000L)
        }
        return this
    }

    override fun destroy(): AtomLocationController {
        isCall = true
        this.manager.destroy()
        return this
    }
}